//
//  DFOauthViewController.swift
//  FlyBlog
//
//  Created by FEI on 16/4/11.
//  Copyright © 2016年 FEI. All rights reserved.
//

import UIKit
import SVProgressHUD

class DFOauthViewController: UIViewController {

    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = GlobalBackgroundColor
        setupNavigationBar()
        //加载授权界面
        let url = oauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)

        //添加alertview
       SVProgressHUD.showInfoWithStatus("正在加载登录界面...")
       SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)


    }
    //拼接授权登录界面url
    private func oauthURL() -> NSURL {
        let URLString = OauthURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        return NSURL(string: URLString)!
    }
    //设置导航栏左右
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("autoFill"))

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
    }
        //按钮点击事件
        @objc private func autoFill() {
             //webview执行js代码  账号密码填充
            let js = "document.getElementById('userId').value = '276113130@qq.com';document.getElementById('passwd').value = '805227'"
            webView.stringByEvaluatingJavaScriptFromString(js)
        }

        @objc private func close() {
            dismissViewControllerAnimated(true, completion: nil)
        }

        //MARK:懒加载webview
        lazy var webView:UIWebView = UIWebView()
}
//MARK:webview代理方法
    extension DFOauthViewController:UIWebViewDelegate {

        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            let URLString  =  request.URL?.absoluteString
//            DFPrint("\(URLString)")
            // 当如果是  http://www.baidu.com/ 开头的地址,我们自己来处理拦截不让他去加载,其他的地址放行
            // 点击取消按钮: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330

            // 点击授权: http://www.baidu.com/?code=4e496956aa012e11299494637e9ca536
            //判断是否是授权回调地址
            let isRedirectURI = URLString!.hasPrefix(redirect_uri)

            if !isRedirectURI {
                return true
            }else {
                //判断授权回调地址,点击的是授权或取消,?后面是code= 就是授权
                let query = request.URL?.query

                let codeString = "code="

                if query!.hasPrefix(codeString) {
//                    DFPrint("授权被点击了:\(query)")

                    let code = (query! as NSString).substringFromIndex(codeString.characters.count)
                    DFPrint("\(code)")
                    DFUserAccountModel.shareInstance.loadAccessToken(code,loadAccessTokenCallback:{(error) -> () in
                        if error != nil {
                            SVProgressHUD.showErrorWithStatus("网络不给力")

                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                                self.close()
                            })
                            return
                        }
                        self.close()
                    })
                }else {
//                    DFPrint("取消按钮被点击了")
                    close()
                }
                return false

            }

        }

//        private func loadAccessToken(code: String) {
//            let URLSring = accessTokenURLString
//
//            let parameters = [
//                "client_id" : client_id,
//                "client_secret" : client_secret,
//                "grant_type" : grant_type,
//                "code" : code,
//                "redirect_uri" : redirect_uri
//            ]
//
//            DFNetworkTool.shareInstance.POST(URLSring, parameters: parameters, progress: nil, success: { (task, responsObject) -> Void in
//
//                DFPrint("请求成功\(responsObject)")
//                }) { (task, error) -> Void in
//
//                    DFPrint("请求失败\(error)")
//            }
        func webViewDidFinishLoad(webView: UIWebView)
        {
            SVProgressHUD.dismiss()
        }


        func webView(webView: UIWebView,didFailLoadWithError error:NSError?) {

            if error?.code == 102 {
                return
            }
            SVProgressHUD.showErrorWithStatus("网络不给力...")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        }
    }



